# app/services/salary_service.py

from app import db
from app.models import Salary
from app.models.user import User
from sqlalchemy import or_

class SalaryService:
    @staticmethod
    def get(salary_id):
        """标准方法：获取单条记录"""
        return SalaryService.get_salary(salary_id)

    @staticmethod
    def list(filters=None, page=1, per_page=10):
        """标准方法：列表查询，带分页"""
        return SalaryService.list_salaries(filters or {}, page, per_page)

    @staticmethod
    def page(filters=None, page=1, per_page=10):
        """标准方法：分页查询（同 list）"""
        return SalaryService.list_salaries(filters or {}, page, per_page)

    @staticmethod
    def create(data):
        """标准方法：创建单条"""
        return SalaryService.create_salary(data)

    @staticmethod
    def update(salary_id, data):
        """标准方法：部分更新"""
        return SalaryService.update_salary(salary_id, data)

    @staticmethod
    def replace(salary_id, data):
        """标准方法：全量替换"""
        return SalaryService.replace_salary(salary_id, data)

    @staticmethod
    def delete(salary_id):
        """标准方法：删除单条"""
        return SalaryService.delete_salary(salary_id)

    @staticmethod
    def batch(data_list):
        """标准方法：批量处理"""
        return SalaryService.batch_create_salaries(data_list)
    @staticmethod
    def get_salary(salary_id):
        return Salary.query.get(salary_id)

    @staticmethod
    def get_salary_detail(salary_id):
        sal = SalaryService.get_salary(salary_id)
        if not sal:
            raise ValueError("记录不存在")
        return sal

    @staticmethod
    def list_salaries(filters, page, per_page):
        query = Salary.query
        kw = filters.get('keyword')
        if kw:
            like_kw = f"%{kw}%"
            query = query.filter(or_(
                Salary.company.ilike(like_kw),
                Salary.position.ilike(like_kw),
                Salary.city.ilike(like_kw),
            ))
        for f in ('company','position','city'):
            if filters.get(f):
                query = query.filter(getattr(Salary, f).ilike(f"%{filters[f]}%"))
        if filters.get('min_salary') is not None:
            query = query.filter(Salary.base_salary >= filters['min_salary'])
        if filters.get('max_salary') is not None:
            query = query.filter(Salary.base_salary <= filters['max_salary'])
        if filters.get('education'):
            query = query.filter(Salary.education == filters['education'])
        if filters.get('type'):
            query = query.filter(Salary.type == filters['type'])
        if filters.get('status'):
            query = query.filter(Salary.status == filters['status'])
        #分页
        pagination = query.order_by(Salary.id.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        return {
            'items': [i.to_dict() for i in pagination.items],
            'total': pagination.total,
            'page': pagination.page,
            'per_page': pagination.per_page,
            'pages': pagination.pages
        }

    @staticmethod
    def search_salaries(filters, page, per_page=2):
        #查询接口
        data = SalaryService.list_salaries(filters, page, per_page)
        return {
            'items': data['items'],
            'total': data['total'],
            'current_page': data['page'],
            'per_page': data['per_page'],
            'pages': data['pages'],
            'has_next': data['page'] < data['pages']
        }

    @staticmethod
    def create_salary(data):
        sal = Salary(**data)
        db.session.add(sal)
        db.session.commit()
        return sal

    @staticmethod
    def create_salary_from_wechat(content, openid):
        """
        解析微信分享格式并创建单条薪资记录
        格式：公司|职位|城市|月薪(k)|月数|年终奖(k)|签字费(k)|股票期权
        """
        parts = content.split('|')
        if len(parts) < 4:
            raise ValueError("分享格式错误，请发送“分享”获取示例")
        company, position, city = parts[0], parts[1], parts[2]
        try:
            base_salary = float(parts[3])
        except:
            raise ValueError("月薪必须为数字")
        months = int(parts[4]) if len(parts) > 4 and parts[4] else 12
        bonus = float(parts[5]) if len(parts) > 5 and parts[5] else 0
        signing = float(parts[6]) if len(parts) > 6 and parts[6] else 0
        stock = parts[7] if len(parts) > 7 and parts[7] else None

        # 从 openid 找到或创建 User
        user = User.query.filter_by(openid=openid).first()
        if not user:
            user = User(openid=openid)
            db.session.add(user)
            db.session.commit()

        data = {
            'user_id': user.id,
            'company': company,
            'position': position,
            'city': city,
            'base_salary': base_salary,
            'months': months,
            'bonus': bonus,
            'signing_bonus': signing,
            'stock': stock,
            'status': 'pending'
        }
        return SalaryService.create_salary(data)

    @staticmethod
    def update_salary(salary_id, data):
        sal = SalaryService.get_salary(salary_id)
        if not sal:
            raise ValueError("记录不存在")
        for k,v in data.items():
            if hasattr(sal, k):
                setattr(sal, k, v)
        db.session.commit()
        return sal

    @staticmethod
    def replace_salary(salary_id, data):
        sal = SalaryService.get_salary(salary_id)
        if not sal:
            raise ValueError("记录不存在")
        for col in Salary.__table__.columns:
            if col.name == 'id': continue
            setattr(sal, col.name, data.get(col.name))
        db.session.commit()
        return sal

    @staticmethod
    def delete_salary(salary_id):
        sal = SalaryService.get_salary(salary_id)
        if not sal:
            raise ValueError("记录不存在")
        db.session.delete(sal)
        db.session.commit()

    @staticmethod
    def batch_create_salaries(data_list):
        objs = [Salary(**d) for d in data_list]
        db.session.bulk_save_objects(objs)
        db.session.commit()
        return objs

    @staticmethod
    def approve_salary(salary_id, password):
        from flask import current_app
        if password != current_app.config['ADMIN_PASSWORD']:
            raise ValueError("管理员密码错误")
        sal = SalaryService.get_salary(salary_id)
        if not sal:
            raise ValueError("记录不存在")
        sal.status = 'approved'
        db.session.commit()
        return sal

    @staticmethod
    def reject_salary(salary_id, password, reason):
        from flask import current_app
        if password != current_app.config['ADMIN_PASSWORD']:
            raise ValueError("管理员密码错误")
        sal = SalaryService.get_salary(salary_id)
        if not sal:
            raise ValueError("记录不存在")
        sal.status = 'rejected'
        sal.remark = (sal.remark or '') + f"\n拒绝原因：{reason}"
        db.session.commit()
        return sal

    @staticmethod
    def verify_admin(password):
        from flask import current_app
        return password == current_app.config['ADMIN_PASSWORD']

    @staticmethod
    def get_pending_salaries_all():
        """
        返回所有状态为 pending 的薪资信息列表（不分页）
        """
        pendings = Salary.query.filter_by(status='pending') \
            .order_by(Salary.id.desc()) \
            .all()
        return [item.to_dict() for item in pendings]